import logging
import os

import allure
import ddddocr
import pytest

from tools.page import page_get

page_screenshot = None
should_skip_all = False


# 实现如果有测试用例失败则跳过其他所有测试用例的功能
def pytest_runtest_makereport(item, call):
    global should_skip_all
    if call.when == 'call' and call.excinfo is not None:
        should_skip_all = True


def pytest_runtest_setup(item):
    if should_skip_all:
        pytest.skip("Skipping due to previous test failure")


@pytest.fixture(scope="session", autouse=True, name='page')
def page_param():
    global page_screenshot
    logging.info('开始启动浏览器')
    page_screenshot = page_get()
    yield page_screenshot
    page_screenshot.quit()
    logging.info('关闭浏览器')


# 实现异常截图
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    rep = outcome.get_result()
    if rep.when == "call" and rep.failed:
        # allure.attach直接将截图二进制数据附加到allure报告中
        allure.attach(page_screenshot.get_screenshot(as_bytes='png', name='异常截图.png', full_page=True), "异常截图",
                      allure.attachment_type.PNG)


@pytest.fixture(scope="function", params=[['18679149706c1', 'yexiong1997']])
def login_聚水潭(request, page):
    logging.info('开始登录')
    page.get("https://www.erp321.com/login.aspx")
    page("#login_id").input(request.param[0])
    page("#password").input(request.param[1])
    page("#agreementCheck").click()
    page('立即登录').click()
    page.wait(5)
    if page('注意：您的密码已经超过3个月未修改(304)，请您尽快修改密码！', timeout=3):
        page('确认').click()
    logging.info('登录成功')
    page.wait(5)


# 识别验证码
def get_captcha(screenshot_path):
    ocr = ddddocr.DdddOcr()
    with open(screenshot_path, 'rb') as f:
        img_bytes = f.read()
    result = ocr.classification(img_bytes)
    return result


@pytest.fixture(scope="function", params=[['zhanhuawei', 'weiwei666']])
def login_ERP(request, page):
    page.get("http://192.168.16.240:8001/rebotlogin")
    logging.info('开始登录')
    page('@placeholder=请输入账号').input(request.param[0])
    page('@placeholder=请输入密码').input(request.param[1])
    os.remove('./imgs/imgs.png')
    page("t:img").save(r".\imgs", name='imgs.png')
    result = get_captcha(r".\imgs\imgs.png")
    page('@placeholder=验证码').input(result)
    page(".el-button el-button--primary el-button--mini is-round").click()
    logging.info('登录成功')
